<template>
  <div class="container">
    <div class="search-container">
      <el-select v-model="searchType" placeholder="选择搜索方式" class="search-select">
        <el-option label="按ID查询" value="id" />
        <el-option label="按名称模糊查询" value="name" />
      </el-select>
      <el-input v-model="searchKeyword" placeholder="请输入搜索关键词" class="search-input" clearable
        @keyup.enter="handleSearch" />
      <el-button type="primary" :icon="Search" @click="handleSearch" class="search-button">
        搜索
      </el-button>
      <el-button type="primary" @click="handleSearchAll" class="search-button">
        查询全部
      </el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="设备编号" width="180" />
      <el-table-column prop="name" label="设备名称" width="180" />
      <el-table-column prop="type" label="设备类型" />
      <el-table-column prop="description" label="设备描述" />
      <el-table-column prop="createTime" label="安装时间" />
      <el-table-column prop="userCount" label="用户数量" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" @click="handleUpdate(scope.row)">更新</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 更新设备的弹窗 -->
    <el-dialog v-model="updateDialogVisible" title="更新设备信息" width="500">
      <el-form :model="updateDevice">
        <el-form-item label="设备名称" :label-width="formLabelWidth">
          <el-input v-model="updateDevice.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="设备类型" :label-width="formLabelWidth">
          <el-input v-model="updateDevice.type" autocomplete="off" />
        </el-form-item>
        <el-form-item label="设备描述" :label-width="formLabelWidth">
          <el-input v-model="updateDevice.description" autocomplete="off" type="textarea" />
        </el-form-item>
        <el-form-item label="用户数量" :label-width="formLabelWidth">
          <el-input-number v-model="updateDevice.userCount" :min="0" />
        </el-form-item>
        <el-form-item label="安装时间" :label-width="formLabelWidth">
          <el-date-picker v-model="updateDevice.createTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpdate">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'
import axios from 'axios'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

interface Device {
  id: number
  name: string
  type: string
  description: string
  createTime: string
  userCount: number
}

const tableData = ref<Device[]>([])
const searchKeyword = ref('')
const searchType = ref<'id' | 'name'>('name')
const formLabelWidth = '100px'

// 搜索处理函数 - 向后端发送请求
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    let params = {}
    if (searchType.value === 'id') {
      const id = Number(searchKeyword.value)
      if (isNaN(id)) {
        ElMessage.warning('请输入有效的数字ID')
        return
      }
      params = { id }
    } else {
      params = { name: searchKeyword.value }
    }

    const response = await axios.get('/api/device/search', { params })

    // 处理不同返回格式
    if (Array.isArray(response.data.data)) {
      // 按名称查询返回的是数组
      tableData.value = response.data.data
    } else {
      // 按ID查询返回的是单个对象，转换为数组
      tableData.value = response.data.data ? [response.data.data] : []
    }

    ElMessage.success(response.data.msg)
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

// 查询全部处理函数
const handleSearchAll = async () => {
  try {
    const response = await axios.get('/api/device/selectAllDevices')
    tableData.value = response.data.data || []
    searchKeyword.value = ''
    ElMessage.success(response.data.msg || '查询成功')
  } catch (error) {
    console.error('查询全部失败:', error)
    ElMessage.error('查询全部失败')
  }
}

// 初始化加载数据
handleSearchAll()

// 更新设备相关逻辑
const updateDialogVisible = ref(false)
const updateDevice = ref<Device>({
  id: 0,
  name: '',
  type: '',
  description: '',
  createTime: '',
  userCount: 0
})

const handleUpdate = (row: Device) => {
  updateDevice.value = { ...row } // 将选中的设备信息复制到更新表单中
  updateDialogVisible.value = true // 打开弹窗
}

// 提交更新
const submitUpdate = async () => {
  try {
    const response = await axios.put('/api/device/updateDeviceById', updateDevice.value)
    ElMessage.success(response.data.msg || '更新成功')
    updateDialogVisible.value = false
    await handleSearchAll() // 刷新列表
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 删除设备逻辑
const handleDelete = async (row: Device) => {
  try {
    await axios.delete(`/api/device/${row.id}`)
    ElMessage.success('删除成功')
    await handleSearchAll()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-select {
  width: 150px;
}

.search-input {
  width: 300px;
}
</style>